# Contributor: Mehdi Chinoune <mehdi.chinoune@hotmail.com>

if [[ $MINGW_PACKAGE_PREFIX == *-clang-* ]]; then
  _clangprefix=1
fi

_realname=polly
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
_pkgver=20.1.5
pkgver=${_pkgver/-/}
pkgrel=1
pkgdesc="Polly - Polyhedral optimizations for LLVM (mingw-w64)"
url="https://polly.llvm.org/"
arch=(any)
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
license=("spdx:Apache-2.0 WITH LLVM-exception")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-llvm"
)
_url=https://github.com/llvm/llvm-project/releases/download/llvmorg-${_pkgver}
_pkgfn=${_realname}-${_pkgver}.src
source=($_url/$_pkgfn.tar.xz{,.sig}
        ${_url}/cmake-${_pkgver}.src.tar.xz{,.sig})
sha256sums=('a6e1789b2239f53daab96c21b982b56532db1bdf3accc17868639434c49ada74'
            'SKIP'
            '1b5abaa2686c6c0e1f394113d0b2e026ff3cb9e11b6a2294c4f3883f1b02c89c'
            'SKIP')
validpgpkeys=('B6C8F98282B944E3B0D5C2530FC3042E345AD05D'  # Hans Wennborg, Google.
              '474E22316ABF4785A88C6E8EA2C794A986419D8A'  # Tom Stellard
              'D574BD5D1D0E98895E3BF90044F2485E45D59042') # Tobias Hieta

prepare() {
  cd "${srcdir}"
  mv cmake-${_pkgver}.src cmake
}

build() {
  mkdir -p build-${MSYSTEM} && cd build-${MSYSTEM}

  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake \
    -GNinja \
    "${_extra_config[@]}" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DCMAKE_SYSTEM_IGNORE_PATH=/usr/lib \
    -DLLVM_HOST_TRIPLE="${CARCH}-w64-windows-gnu" \
    -DPython3_EXECUTABLE=${MINGW_PREFIX}/bin/python.exe \
    -DLLVM_LINK_LLVM_DYLIB=ON \
    -Wno-dev \
    ../$_pkgfn

  ${MINGW_PREFIX}/bin/cmake --build .
}

package() {
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install build-${MSYSTEM}

  # fix cmake files.
  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  local SRC_WIN=$(cygpath -wm "${srcdir}")
  sed -e "s|${PREFIX_WIN}|${MINGW_PREFIX}/|g" \
    -e "s|${SRC_WIN}/build-${MSYSTEM}/lib|${MINGW_PREFIX}/lib|g" \
    -i "${pkgdir}/${MINGW_PREFIX}/lib/cmake/polly/PollyConfig.cmake"

  install -Dm644 $_pkgfn/LICENSE.TXT "${pkgdir}"${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE
}
